package cn.anc.aonicardv.module.ui.recorder;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.anc.aonicardv.Constant;
import cn.anc.aonicardv.R;
import cn.anc.aonicardv.R2;
import cn.anc.aonicardv.bean.VideoBean;
import cn.anc.aonicardv.event.PlayVideoDataEvent;
import cn.anc.aonicardv.media.PlayerController;
import cn.anc.aonicardv.media.PlayerVideoView;
import cn.anc.aonicardv.module.ui.MainActivity;
import cn.anc.aonicardv.module.ui.base.BaseActivity;
import cn.anc.aonicardv.param.ParamManager;
import cn.anc.aonicardv.util.DeviceInfo;
import cn.anc.aonicardv.util.DialogUtils;
import cn.anc.aonicardv.util.LogUtil;
import cn.anc.aonicardv.util.SpUtils;
import cn.anc.aonicardv.widget.WarningDialog;
import cn.anc.httpcontrolutil.CarControl;
import cn.anc.httpcontrolutil.cache.CacheManager;
import tv.danmaku.ijk.media.player.IMediaPlayer;

/**
 * Created by yangdai on 2017/5/23.
 */

public class RecorderPlayVideoActivity extends BaseActivity implements View.OnClickListener, CarControl.OnHeartBeatCallBack, CarControl.OnCardvThumbnailCallback {

    @BindView(R2.id.ll_exit)
    LinearLayout llExit;
    @BindView(R2.id.tv_title_name)
    TextView tvTitle;
    @BindView(R2.id.player)
    PlayerVideoView playerVideoView;
    private List<VideoBean> videoBeanList;
    public int currentPosition;
    private WarningDialog warningDialog;
    public CarControl.CarDvThumbnailMediaInfo mediaInfo;
    private Handler handler;
    private DialogUtils dialogUtils;
    private PlayerController playerController;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_recorder_play_video);
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }

    @Override
    public void initVariable() {
        tvTitle.setVisibility(View.GONE);
        dialogUtils = new DialogUtils();
        warningDialog = dialogUtils.getWarningDialog(this);
        setLayoutSize(playerVideoView, DeviceInfo.ScreenHeightPixels * 16 / 9, DeviceInfo.ScreenHeightPixels);
        handler = new Handler();
        playerController = new PlayerController(this);
        playerController.setFullScreenBtnVisibility(false);
        ProgressBar bufferingBar = new ProgressBar(this);
        playerVideoView.setMediaController(playerController);
        playerVideoView.setMediaBufferingIndicator(bufferingBar, new FrameLayout.LayoutParams(150, 150, Gravity.CENTER));
    }

    private void setLayoutSize(View view, int width, int height) {
        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) view.getLayoutParams();
        lp.width = width;
        lp.height = height;
        view.setLayoutParams(lp);
    }

    @Override
    protected void onResume() {
        super.onResume();
        playerVideoView.onResume();
        CarControl.setOnHeartBeatCallBack(this);
        if (!CarControl.IsConnected.get()) {
            if (null != warningDialog) {
                if (warningDialog.isShowing()) {
                    warningDialog.dismiss();
                }
                if (!warningDialog.isShowing() && !isDestroyed()) {
                    warningDialog.setHint(getString(R.string.tip_cardv_disconnect)).show();
                }
            }
        }
    }



    @Override
    public void setListener() {
        warningDialog.okTv.setOnClickListener(this);
        playerController.setOnFullScreenClickListener(onFullScreenClickListener);
        playerController.setOnPlayLastClickListener(onPlayLastClickListener);
        playerController.setOnPlayNextClickListener(onPlayNextClickListener);
        playerController.setOnVideoBackListener(onVideoBackListener);
        playerController.setOnPlayStatusListener(onPlayStatusListener);
        playerController.setOnPlayClickListener(playClickListener);
        playerVideoView.setOnCompletionListener(onCompletionListener);
    }

    @Override
    public void initData() {
        SpUtils.putString(Constant.SpKeyParam.APP_LOG, "");
    }

    @OnClick(R2.id.ll_exit)
    public void back() {
        finish();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (null != playerVideoView) {
            playerVideoView.onPause();
        }
    }


    @Override
    protected void onDestroy() {
        if (null != playerVideoView) {
            playerVideoView.releasePlayer();
        }
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }


    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onMessageEvent(PlayVideoDataEvent event) {
        videoBeanList = event.bean;
        currentPosition = Integer.valueOf(getIntent().getStringExtra(Constant.IntentKeyParam.POSITION));
        resetPlayerAndRefreshUi(currentPosition);
    }


    @Override
    public void onClick(View v) {
        warningDialog.dismiss();
        startActivity(new Intent(this, MainActivity.class));
    }


    private void resetPlayerAndRefreshUi(int position) {
        String mPath = getVideoPath(position);
        LogUtil.e("llcTest", "---getPath---mPath-:" + mPath);
        if (playerVideoView != null) {
            playerVideoView.releasePlayer();
            playerVideoView.setDataSource(mPath);
            playerVideoView.start();
        }
        String remotePath = videoBeanList.get(position).getPath();
        String path = CacheManager.getCachePath(remotePath);
        File file = new File(path);
        playerController.setThumbnail(file.getAbsolutePath());
        updateTitle(position);
    }

    @Override
    public void OnThumbnailGetted(int index) {
        CarControl.CarDvThumbnailMediaInfo mediaInfo = CacheManager.getMediaInfoFromExif(CacheManager.getCachePath(videoBeanList.get(currentPosition).getPath()));
        if (mediaInfo != null) {
            tvTitle.setVisibility(View.GONE);
            tvTitle.setText(mediaInfo.file_time);

        }
    }

    private void loadVideoThumbs(int position) {
        List<Integer> idxArray = new ArrayList<>();
        if (!CacheManager.checkCacheExist(videoBeanList.get(position).getPath())) {
            List<VideoBean> mLoadBean = new ArrayList<>();
            mLoadBean.add(videoBeanList.get(position));
            idxArray.add(0);
            CarControl.doGetVideoThumbnail(mLoadBean, idxArray, RecorderPlayVideoActivity.this);
        }
    }


    private void updateTitle(int position) {
        CarControl.CarDvThumbnailMediaInfo mediaInfo = CacheManager.getMediaInfoFromExif(CacheManager.getCachePath(videoBeanList.get(position).getPath()));
        if (mediaInfo != null) {
            tvTitle.setVisibility(View.GONE);
            tvTitle.setText(mediaInfo.file_time);
        } else {
            loadVideoThumbs(position);
        }
    }

    @Override
    public void OnHeartBeatConnectOK() {
    }

    @Override
    public void OnHeartBeatConnectFail() {
    }

    @Override
    public void OnHeartBeatDisconnect() {
        if (null != playerVideoView) {
            playerVideoView.releasePlayer();
        }
        //停留0.5s钟等待  等待view加载完毕
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (null != warningDialog)
                    warningDialog.setHint(getString(R.string.tip_cardv_disconnect)).show();
            }
        }, 500);

    }


    private String getVideoPath(int position) {
        VideoBean videoBean = videoBeanList.get(position);
        return ParamManager.CarServerParam.http_base_url + videoBean.getPath();
    }

    PlayerController.OnPlayLastClickListener onPlayLastClickListener = new PlayerController.OnPlayLastClickListener() {
        @Override
        public void onPlayLastClick() {
            if (currentPosition > 0) {
                currentPosition--;
                resetPlayerAndRefreshUi(currentPosition);
            }
        }
    };

    PlayerController.OnPlayNextClickListener onPlayNextClickListener = new PlayerController.OnPlayNextClickListener() {
        @Override
        public void onPlayNextClick() {
            if (currentPosition < videoBeanList.size() - 1) {
                currentPosition++;
                resetPlayerAndRefreshUi(currentPosition);
            }
        }
    };

    PlayerController.OnFullScreenClickListener onFullScreenClickListener = new PlayerController.OnFullScreenClickListener() {
        @Override
        public void onFullScreenClick() {

        }
    };

    PlayerController.OnVideoBackListener onVideoBackListener = new PlayerController.OnVideoBackListener() {
        @Override
        public void back() {
            finish();
        }
    };


    PlayerController.OnPlayStatusListener onPlayStatusListener = new PlayerController.OnPlayStatusListener() {
        @Override
        public void onPlayStatus(int status) {
            if (status == PlayerController.STATE_PLAYING) {
                playerController.setTitle("");
            }
        }
    };

    PlayerController.OnPlayClickListener playClickListener = new PlayerController.OnPlayClickListener() {
        @Override
        public boolean onPlayClick() {
            return false;
        }
    };

    IMediaPlayer.OnCompletionListener onCompletionListener = new IMediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(IMediaPlayer mp) {
            if (currentPosition < videoBeanList.size() - 1) {
                currentPosition++;
                resetPlayerAndRefreshUi(currentPosition);
            }
        }
    };


}
